//
//  XGL_PersonalRechargeViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/31.
//

import UIKit
import CollectionKit

class XGL_PersonalRechargeViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var currentCoinText: UILabel!
    var collectionView: CollectionView!
    var coinDatas: ArrayDataSource<RechargeCoinData> = ArrayDataSource(data: [])
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.setCollectionData()
        self.creatClearNavigationBar(title: "")
        self.getRechargeListRequest()
        self.getCoinDataRequest()
    }
    

}

extension XGL_PersonalRechargeViewController{
    @objc private func rechargeAction(){
        guard let selectItem = self.coinDatas.data.first(where: {$0.isSelected}) else { return  }
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        XGL_PurchaseManager.share.pay(purchaseProductId: selectItem.code) { result in
            self.hudView.dismiss()
            if result {
                MXProgressHUD.hudWithText("Recharge successfully")
                self.getCoinDataRequest()
            }
        }
    }
    
    @objc private func selectItemAction(sender: UIButton){
        let index = sender.tag - 3000
        var datas = self.coinDatas.data.map { item in
            var data = item
            data.isSelected = false
            return data
        }
        datas[index].isSelected = true
        self.coinDatas.data = datas
    }
}

extension XGL_PersonalRechargeViewController{
    private func getCoinDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CoinData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .SurplusCoin)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.currentCoinText.text = Double(data.amount).roundTo(places: 2).description
                }
                break
            default:
                break
            }
        }
    }
    private func getRechargeListRequest(){
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<RechargeCoinData>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .rechargeList)) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let datas = response.resultDatas {
                    self.coinDatas.data = datas
                    self.collectionView.snp.updateConstraints { make in
                        make.height.equalTo(ceil(Double(datas.count) / 3.0) * 116.0)
                    }
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalRechargeViewController{
    private func createXglView(){
        let coinBackImageView = UIImageView().then { make in
            make.image = imageWithName("icon_xgl_personal_recharge_bg")
        }
        let storeText = UILabel().then { make in
            make.text = "Coin Store"
            make.font = UIFont.pingfangSC_Semibold(fontSize: 36.0)
            make.textColor = UIColor.hexColor("#001310")
        }
        let coinTitleText = UILabel().then { make in
            make.text = "My balance"
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            make.textColor = UIColor.hexColor("#001310")
        }
        self.currentCoinText = UILabel().then { make in
            make.text = "0.0"
            make.font = UIFont.pingfangSC_Medium(fontSize: 40.0)
            make.textColor = UIColor.hexColor("#191A1D")
        }
        self.collectionView = CollectionView()
        let button = UIButton().then { make in
            make.setTitle("To pay", for: .normal)
            make.setTitleColor(UIColor.hexColor("#191A1D"), for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.backgroundColor = UIColor.hexColor("#80FFE6")
            make.layerCornerRadius = 24.0
            make.addTarget(self, action: #selector(self.rechargeAction), for: .touchUpInside)
        }
        self.view.addSubviews([coinBackImageView,storeText,coinTitleText,currentCoinText,collectionView,button])
        coinBackImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalTo(15.0)
            make.top.equalTo(conversionWithScrennWidth(value: 102.0))
            make.height.equalTo(coinBackImageView.snp.width).multipliedBy(173.0/345.0)
        }
        storeText.snp.makeConstraints { make in
            make.left.equalTo(coinBackImageView.snp.left).offset(16.0)
            make.top.equalTo(coinBackImageView.snp.top).offset(20.0)
        }
        coinTitleText.snp.makeConstraints { make in
            make.left.equalTo(coinBackImageView.snp.left).offset(16.0)
            make.bottom.equalTo(self.currentCoinText.snp.top).offset(-6.0)
        }
        self.currentCoinText.snp.makeConstraints { make in
            make.left.equalTo(coinBackImageView.snp.left).offset(16.0)
            make.bottom.equalTo(coinBackImageView.snp.bottom).offset(-16.0)
        }
        collectionView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.left.equalTo(11.0)
            make.top.equalTo(coinBackImageView.snp.bottom).offset(4.0)
            make.height.equalTo(0.0)
        }
        button.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(conversionWithScrennWidth(value: 345.0))
            make.height.equalTo(48.0)
            make.bottom.equalTo(-BottomHeight-48.0)
        }
    }
    
    func setCollectionData(){
        let viewSource = ClosureViewSource(viewUpdater: { [weak self] (view: UIView, data: RechargeCoinData, index: Int) in
            guard let `self` = self else { return }
            view.backgroundColor = .clear
            view.removeSubviews()
            let contentView = UIView().then { make in
                make.layerBorderColor = UIColor.hexColor("#83FFE7")
                make.layerBorderWidth = data.isSelected ? 1.0 : 0.0
                make.layerCornerRadius = 12.0
                make.backgroundColor = UIColor.hexColor("#001310").withAlphaComponent(0.5)
            }
            let iconView = UIImageView().then { make in
                make.image = imageWithName("icon_xgl_gift_coin")
            }
           
            let coinLabel = UILabel().then({ make in
                make.textColor = UIColor.white
                make.text = "\(data.gold)"
                make.font = UIFont.pingfangSC_Regular(fontSize: 24.0)
            })
            let priceLabel = UILabel().then({ make in
                make.textColor = UIColor.hexColor("#DBDBDB")
                make.text = "$\(Double(data.price).roundTo(places: 2))"
                make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            })
            let itemButton = UIButton().then { make in
                make.tag = index + 3000
                make.addTarget(self, action: #selector(self.selectItemAction(sender:)), for: .touchUpInside)
            }
            let goldItemView = UIView()
            goldItemView.addSubviews([iconView,coinLabel])
            contentView.addSubviews([goldItemView,priceLabel,itemButton])
            view.addSubview(contentView)
            iconView.snp.makeConstraints { make in
                make.left.centerY.equalToSuperview()
                make.width.height.equalTo(28.0)
            }
            coinLabel.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.left.equalTo(iconView.snp.right).offset(8.0)
            }
            goldItemView.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(contentView.snp.centerY).offset(-8.0)
                make.right.equalTo(coinLabel)
                make.height.equalTo(28.0)
            }
            priceLabel.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(contentView.snp.centerY).offset(8.0)
            }
            itemButton.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            contentView.snp.makeConstraints { make in
                make.left.equalTo(4.0)
                make.top.equalTo(8.0)
                make.center.equalToSuperview()
            }
        })
        let sizeSource = { (index: Int, data: RechargeCoinData, collectionSize: CGSize) -> CGSize in
            
            return CGSize(width: collectionSize.width / 3.0, height: 116.0)
        }
        let provider = BasicProvider(
            dataSource: self.coinDatas,
            viewSource: viewSource,
            sizeSource: sizeSource
        )
        self.collectionView.provider = provider
    }
}
